#!/usr/bin/env python
# -*- coding:utf-8 -*-  
import logging
from google.appengine.ext import webapp
from google.appengine.ext.webapp.mail_handlers import InboundMailHandler
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.api import mail
import cgi
import wsgiref.handlers
from google.appengine.api import users
from google.appengine.ext import db
from google.appengine.api import urlfetch
import urllib # Used to unescape URL parameters.
from email.Header import decode_header
from email.utils import parseaddr
try:
  from xml.etree import ElementTree
except ImportError:
  from elementtree import ElementTree
import getopt
import sys
import string
import time
from model import People, Message
import base64

def code2utf(subject):
    _subject_list=decode_header(subject)
    if (_subject_list[0][1]):
      _subject = _subject_list[0][0].decode(_subject_list[0][1]).encode("utf-8")
    else :
      _subject = _subject_list[0][0]
    return _subject
def sender2str(sender):
    sender=parseaddr(sender)
    sender_name=code2utf(sender[0])
    sender_email=code2utf(sender[1])
    return sender_name+"<"+sender_email+">"
    
class Greeting(db.Model):
  author = db.UserProperty()
  content = db.StringProperty(multiline=True)
  date = db.DateTimeProperty(auto_now_add=True)

    
class MailHandler(InboundMailHandler):
  def receive(self, message):
    if code2utf(parseaddr(message.subject)[1]) in ['mail-noreply@google.com']:
      rmessage=message
      rmessage.to=""
      rmessage.send()
    else:
      to1=message.to
      bodies=message.bodies(content_type='text/plain')
      allBodies = "";
      for body in bodies:
        allBodies = allBodies + "\n---------------------------\n" + body[1].decode()
        if isinstance(allBodies, unicode):
          allBodies = allBodies.encode('utf-8')
      _sender=sender2str(message.sender)

      for line1 in to1.split(','):
        line2= line1.split('@')
        if line2[1]=='hvufee.appspotmail.com':
            line3= line2[0].split('.')
            all_1=line3[1]+'\n'+code2utf(message.subject)+'\n'+  _sender+'\n'+allBodies

            message = Message(nickname=line3[0])
            message.content = base64.encodestring(all_1)
            message.put()

application = webapp.WSGIApplication([
  MailHandler.mapping()
], debug=True)
def main():
  run_wsgi_app(application)
if __name__ == "__main__":
  main()
